const DB = require('./db');
const eventEmitter = require('./events');

module.exports = async (req, res, next) => {
	// 设置响应头，告诉浏览器这是一个 SSE 请求
	res.setHeader('Content-Type', 'text/event-stream');
	res.setHeader('Cache-Control', 'no-cache');
	res.setHeader('Connection', 'keep-alive');
	res.setHeader('Transfer-Encoding', 'chunked');

	// 实时用户省份统计
	let [provinceList] = await DB.query(`select province,count(1) num from t_user where type=1 group by province`);

	// 用户数量
	let [userList] = await DB.query(`select count(1) num from t_user where type=1 `);

	// 实时在线访客
	let [visitorList] = await DB.query(`select *, date_format(updateTime,'%Y-%m-%d %H:%i:%s') updateTime from t_visitor where type=1 order by updateTime desc limit 1`);
	let visitorObj = {};

	if (!visitorList.length) {
		visitorObj = {
			avatar: '/uploads/avatar/nv.png',
			username: '暂无人访问',
			ip: 1,
			time: '-',
			address: '-',
			ips: '-'
		};
	} else {
		if (visitorList[0].userId) {
			let [user] = await DB.query(`select * from t_user where id=${visitorList[0].userId}`);
			visitorObj = {
				avatar: user[0].avatar,
				username: user[0].username,
				ip: visitorList[0].ip,
				time: visitorList[0].updateTime,
				address: visitorList[0].country + visitorList[0].province + visitorList[0].city,
				ips: visitorList[0].isp
			};
		} else {
			visitorObj = {
				avatar: '/uploads/avatar/nv.png',
				username: '游客',
				ip: visitorList[0].ip,
				time: visitorList[0].updateTime,
				address: visitorList[0].country + visitorList[0].province + visitorList[0].city,
				ips: visitorList[0].isp
			};
		}
	}

	let sendData = { mapList: provinceList, visitorObj, userNums: userList[0].num };

	res.write(`data: ${JSON.stringify({ message: sendData })}\n\n`);

	const listener = (visitorObj) => {
		sendData = { mapList: provinceList, visitorObj, userNums: userList[0].num };
		res.write(`data: ${JSON.stringify({ message: sendData })}\n\n`);
	};

	const listenerUserNum = ({ userNums, provinceList }) => {
		sendData = { mapList: provinceList, visitorObj, userNums };
		res.write(`data: ${JSON.stringify({ message: sendData })}\n\n`);
	};

	eventEmitter.on('online', listener);
	eventEmitter.on('userNums', listenerUserNum);

	// 客户端断开连接时清理资源
	req.on('close', () => {
            console.log('SSE断开连接');
            
		eventEmitter.removeListener('online', listener);
		eventEmitter.removeListener('userNums', listener);
		res.end();
	});
};
